#include "game.h"
#include <QPainter>
#include <QKeyEvent>

Game::Game(QWidget *parent)
    : QWidget(parent), character_x_(20), character_y_(200), object_x_(600),
      object_y_(200), timer_(new QTimer(this)), is_game_over_(false) {//设置窗口大小并初始化角色和方块位置
  setFixedSize(800, 400);//设置定时器，每50ms触发一次移动角色和产生方块的函数
  timer_->setInterval(50);
  connect(timer_, SIGNAL(timeout()), this, SLOT(moveCharacter()));
  connect(timer_, SIGNAL(timeout()), this, SLOT(spawnObject()));
  timer_->start();
}

void Game::paintEvent(QPaintEvent *event) {
  Q_UNUSED(event);

  QPainter painter(this);
  painter.drawPixmap(0,0,800,500,QPixmap(":/new/img/nice.jpg"));//画背景//

  if (is_game_over_) {//游戏结束，显示“游戏结束”的文字
    painter.drawText(rect(), Qt::AlignCenter, "游戏结束");
    return;
  }

  drawCharacter(painter);
  drawObject(painter);
}

void Game::keyPressEvent(QKeyEvent *event) {
  switch (event->key()) {
  case Qt::Key_Up://上键，向上移动
    character_y_ -= 20;
    break;
  case Qt::Key_Down://下键，向下移动
    character_y_ += 20;
    break;
  case Qt::Key_Left:
    character_x_ -= 20;//左键，向左移动
    break;
  case Qt::Key_Right:
    character_x_ += 20;//右键，向右移动
    break;
  default://其他键，继续处理
    QWidget::keyPressEvent(event);
  }
//检查是否超出边界，如果是则游戏结束
  if (character_x_ < -10 || character_x_ > width() || character_y_ < -10 ||
      character_y_ > height()) {
    is_game_over_ = true;
  }
  update();
}

void Game::drawCharacter(QPainter &painter) {
  painter.setBrush(Qt::black);
  painter.drawEllipse(character_x_, character_y_, 20, 20);
}

void Game::drawObject(QPainter &painter) {
  painter.setBrush(Qt::red);
  painter.drawRect(object_x_, object_y_, 20, 20);
}

void Game::moveCharacter() {
  checkCollision();
  if (!is_game_over_) {//让角色每次向右移动5个像素
    character_x_ += 5;
    update();
  }
}

void Game::spawnObject() {
  if (!is_game_over_) {//让方块每次向左移动10个像素
    object_x_ -= 10;//如果方块已经移到窗口外，则重新从右侧随机产生
    if (object_x_ < -30) {
      object_x_ = width();
      object_y_ = qrand() % (height() - 20);
    }
    update();
  }
}

void Game::checkCollision() {
  if (character_x_ + 20 >= object_x_ && character_x_ <= object_x_ + 20 &&
      character_y_ + 20 >= object_y_ && character_y_ <= object_y_ + 20) {
    is_game_over_ = true;
  }
}
